package web;

import domain.User;
import org.apache.commons.beanutils.BeanUtils;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/updateServlet")
public class UpdateServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //需求:修改用户的信息因为是修改,所以用户的所有的数据都进行更新,避免判断的麻烦
        //解决乱码
        request.setCharacterEncoding("utf-8");
        //处理由update.jsp中的数据
        Map<String, String[]> parameterMap = request.getParameterMap();
        //使用内省技术将数据封装到javabean中
        User user = new User();
        try {
            BeanUtils.populate(user, parameterMap);
            UserServiceImpl service = new UserServiceImpl();
            boolean boo = service.updateUser(user);
            //修改成功之后,页面重新跳转到/queryListServlet,进行查询并显示.
            if (boo){
                response.sendRedirect("/queryListServlet");//重定向,浏览器地址栏发生变化
            }else {
                request.getSession().setAttribute("msg","修改失败");
                response.sendRedirect("/error");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
